// 选项卡切换
let btns = document.querySelectorAll('.main > .content > .main_right > .right_top > p')
let boxs = document.querySelectorAll('.main > .content > .main_right > ul > li')

for (let i = 0; i < btns.length; i++) {
    btns[i].dataset.index = i
    btns[i].onclick = handler
}

function handler() {
    let index = this.dataset.index - 0
    for (let i = 0; i < btns.length; i++) {
        boxs[i].classList.remove('active')
    }
    boxs[index].classList.add('active')
}

const form = document.querySelector('.main > .content > .main_right > ul > li:nth-child(2) > form')
const nameInp = document.querySelector('.main > .content > .main_right > ul > li:nth-child(2) > form > input:nth-child(3)')
const pwdInp = document.querySelector('.main > .content > .main_right > ul > li:nth-child(2) > form > input:nth-child(4)')
const errBox = document.querySelector('.err')
let register = document.querySelector('.main > .content > .main_right > p')


register.onclick = function () {
  window.location.href = './register.html'
}

form.addEventListener('submit', e => {
  e = e || window.event
  try { e.preventDefault() } catch(err) { e.returnValue = false }

  const name = nameInp.value
  const pwd = pwdInp.value

  if (!name || !pwd) return alert('请完整填写表单')

  const xhr = new XMLHttpRequest()
  xhr.open('POST', 'http://localhost:8888/users/login')
  xhr.onload = function () {
    const res = JSON.parse(xhr.responseText)

    loginHandler(res)
  }

  xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')

  xhr.send(`username=${ name }&password=${ pwd }`)
})


function loginHandler(res) {
  if (res.code === 0) {
    errBox.style.display = 'block'
  }

  if (res.code === 1) {
    window.localStorage.setItem('token', res.token)
    window.localStorage.setItem('id', res.user.id)

    window.location.href = './index.html'
  }
}